﻿@page "/setting/role"
@using AntDesign.TableModels
@inject IUserBasics iUserBasics
@inject IRoleBasics iRoleBasics
@inject IMenu iMenu
@inject IRoleMenu iRoleMenu
<Button OnClick="AddItem" Type="primary" Style="margin-bottom:16px">
    Add a user
</Button>
<Table @ref="table"
       TItem="Data"
       DataSource="@data"
       Total="pagination.records"
       @bind-PageIndex="pagination.page"
       @bind-PageSize="pagination.rows"
       @bind-SelectedRows="selectedRows" ScrollX="1200" ScrollY="500" Loading="_loading" OnChange="HandleTableChange">
    @*<Selection Key="@(context.Id.ToString())" />*@
    <Column @bind-Field="@context.RoleName" />
    <Column @bind-Field="@context.RoleCreateTime" Format="yyyy-MM-dd" Sortable />
    <ActionColumn>
        <Space>
            <SpaceItem>
                <Button Type="@ButtonType.Link" Danger OnClick="_ => EditItem(context)">
                    Edit
                </Button>
            </SpaceItem>
        </Space>
        <Space>
            <SpaceItem><Button Danger OnClick="()=>Delete(context.Id)">Delete</Button></SpaceItem>
        </Space>
    </ActionColumn>
</Table>
<Drawer Closable="true" Width="800" Visible="visible" Title=DrawerTitle OnClose="_=>closeDrawer()">
    <Template style="height:90%">
        <Form Model="@datarole"
              LabelColSpan="8"
              WrapperColSpan="16"
              OnFinish="OnFinish"
              Size="@AntSizeLDSType.Default">

            <FormItem Label="角色名称">
                <Input @bind-Value="@context.RoleName" />
            </FormItem>

            <FormItem Label="权限菜单">
                <Tree Checkable
                      DataSource="option"
                      TitleExpression="x=>x.DataItem.MenuName"
                      ChildrenExpression="x=>x.DataItem.MenuOptions"
                      IsLeafExpression="x=>x.DataItem.MenuOptions?.Count==0"
                      KeyExpression="x=>x.DataItem.MenuID.ToString()"
                      Multiple="true"
                      @bind-CheckedKeys="@context.rolemenukey"
                      DefaultCheckedKeys="@context.rolemenukey"
                      TItem="MenuListOpetions">


                </Tree>
            </FormItem>


            <FormItem WrapperColOffset="8" WrapperColSpan="16">
                <Button HtmlType="submit">
                    Submit
                </Button>
            </FormItem>
        </Form>
    </Template>
</Drawer>

<style>
    .ant-form-item-label {
        flex: 0 0 130px !important;
    }

    .ant-col-offset-8 {
        margin-left: 130px;
    }


    .add-icon {
        border: 1px solid #abaaaa;
        color: #797777;
        border-radius: 50%;
        width: 24px;
        height: 24px;
        text-align: center;
        line-height: 24px;
        margin-top: 4px;
        margin-left: 20px;
        padding-right: 1px;
        cursor: pointer;
    }
</style>

@code {
    WindowsHelper windows;
    List<MenuListOpetions> option = new List<MenuListOpetions>();
    bool _loading = false;
    private string _sizeValue = AntSizeLDSType.Default;
    List<Data> forecasts = new List<Data>();
    IEnumerable<Data> selectedRows;
    ITable table;
    Core.DataAccess.Model.Pagination pagination = new Core.DataAccess.Model.Pagination
    {
        page = 1,
        rows = 8
    };
    bool visible = false;
    string DrawerTitle = "Add User";
    int selectRowId = 0;
    Data datarole = new Data
    {
    };

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            windows = new WindowsHelper(jSRuntime);
            await this.LoadData();
            await windows.HideLoadingAsync();
            await windows.SetTitleAsync("Role");
            _ = InvokeAsync(StateHasChanged);
        }
    }


    void closeDrawer()
    {
        this.visible = false;
        this.DrawerTitle = "Add User";
        this.selectRowId = 0;
    }
    void OnSelect(TreeEventArgs<string> args)
    {
        Console.WriteLine($"OnSelect {args.Node.Key}");
    }

    void OnCheck(TreeEventArgs<string> args)
    {
        Console.WriteLine($"OnCheck {args.Node.Key}");
    }
    private async Task HandleTableChange(QueryModel<Data> queryModel)
    {
        if (windows != null)
        {
            this.pagination.page = queryModel.PageIndex;
            this.pagination.rows = queryModel.PageSize;
            await this.LoadData();
        }
    }

    private async Task LoadData()
    {
        this._loading = true;
        await base.InvokeAsync(async () =>
        {
            this.option = await iMenu.GetMenuList();
            this.data = new List<Data>();
            var result = await iRoleBasics.GetSysRoles(pagination);
            var resultrolemenu = await iRoleMenu.Get(new GetRoleMenuRequset
            {
                RoleId = 0
            });
            foreach (var item in result)
            {
                this.data.Add(this.GetRoleDataFormat(item, resultrolemenu.RoleMenus));
            }
            this._loading = false;
            base.StateHasChanged();
        });
    }
    void SelectedNodeChanged(TreeNode<string> e)
    {
        Console.WriteLine($"SelectedNodeChanged: {e?.Key}");
    }

    public async Task<List<SysUser>> GetForecastAsync()
    {
        var result = await iUserBasics.GetSysUsers(pagination);

        return result;

    }

    Data GetRoleDataFormat(SysRole item, List<SysRoleMenu> rolemenu)
    {
        string[] keys = null;
        if (rolemenu.Count > 0)
        {
            var rolefir = rolemenu.Where(a => a.RoleMenuRoleId == item.RoleId).FirstOrDefault();
            if (rolefir != null && !string.IsNullOrEmpty(rolefir.RoleMenuMenuIds))
            {
                keys = rolefir.RoleMenuMenuIds.Split(',').Where(s => !string.IsNullOrEmpty(s)).ToArray();
            }

        }
        var result = new Data
        {
            Id = item.RoleId,
            RoleName = item.RoleName,
            RoleCreateTime = item.RoleCreateTime,
            rolemenukey = keys,
        };
        return result;
    }

    private async void OnFinish(EditContext editContext)
    {
        if (await this.DataValidation())
        {
            bool isSuccess = false;
            string merrorMessage = string.Empty;
            // submit
            await base.InvokeAsync(async () =>
            {
                if (selectRowId == 0)
                {
                    var result = await this.iRoleBasics.RegisterAsync(new RoleRegisterRequset()
                    {
                        RoleName = this.datarole.RoleName,
                        RoleIsDelete = 0,
                        RoleCreateTime = DateTime.Now,
                        RoleMenuId = this.datarole.rolemenukey != null ? string.Join(",", this.datarole.rolemenukey) : "",
                    });
                    if (result.IsSuccessful)
                    {
                        isSuccess = true;
                        pagination.records++;
                    }
                    else
                    {
                        merrorMessage = result.Description;
                    }
                }
                else
                {
                    var requests = new RoleModifyRequset()
                    {
                        RoleId = this.datarole.Id,
                        RoleName = this.datarole.RoleName,
                        RoleIsDelete = 0,
                        RoleCreateTime = DateTime.Now,
                        RoleMenuId = this.datarole.rolemenukey != null ? string.Join(",", this.datarole.rolemenukey) : "",
                    };
                    var result = await this.iRoleBasics.ModifyAsync(requests);
                    if (result.IsSuccessful)
                    {
                        isSuccess = true;
                        pagination.records++;
                    }
                    else
                    {
                        merrorMessage = result.Description;
                    }

                }

                if (isSuccess)
                {
                    // 更新UI
                    base.StateHasChanged();

                    var task = notice.Success(new NotificationConfig
                    {
                        Message = "保存成功"
                    });
                }
                else
                {
                    var task = notice.Error(new NotificationConfig
                    {
                        Message = "操作失败请重试",
                        Description = merrorMessage
                    });
                }
            });
        }


    }
    private async void Delete(int id)
    {
        var result = await iRoleBasics.Delete(new RoleDeleteRequset()
        {
            RoleId = id,

        });
        if (result.IsSuccessful)
        {
            base.StateHasChanged();

            var task = notice.Success(new NotificationConfig
            {
                Message = "删除成功"
            });
        }
        else
        {
            var task = notice.Error(new NotificationConfig
            {
                Message = "操作失败请重试",
                Description = result.Description
            });
        }
    }

    void AddItem()
    {
        this.datarole = new Data();
        this.DrawerTitle = "Add Role";
        this.selectRowId = 0;
        this.visible = true;
    }
    void EditItem(Data item)
    {
        //task(item.Id);
        this.datarole = item;
        this.DrawerTitle = "Edit Role";
        this.selectRowId = item.Id;
        this.visible = true;
    }

    private async Task<bool> DataValidation()
    {
        var message = new NotificationConfig
        {
            Message = "数据验证失败"
        };

        if (string.IsNullOrWhiteSpace(this.datarole.RoleName))
        {
            message.Description = "请填写角色名称";
        }


        if (message.Description.Value != null)
        {
            await notice.Error(message);
            return false;
        }
        return true;
    }
}

@code{

    List<Data> data = new List<Data>();

    public class Data
    {
        public int Id { get; set; }
        [DisplayName("角色名称")]
        public string RoleName { get; set; }
        [DisplayName("角色创建时间")]
        public DateTime? RoleCreateTime { get; set; }
        public string[] rolemenukey { get; set; }
    }
}
